package com.dubbo.server.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.dubbo.server.config.AdminThreadLocal;
import com.dubbo.server.pojo.Admin;
import com.dubbo.server.service.AdminService;
import com.dubbo.server.util.NoAuthorization;
import com.dubbo.server.vo.AdminVo;
import com.dubbo.server.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("management/system/users")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;


    /**
     * 生成验证码图片
     *
     * @param uuid
     */
    @GetMapping("verification")
    @NoAuthorization
    public void verification(@RequestParam("uuid") String uuid, HttpServletResponse response) throws IOException {
        // 禁止浏览器缓存 0秒过期
        response.setDateHeader("Expires", 0);
        //Cache-Control指定请求和响应遵循的缓存机制
        //禁止缓存  必须验证
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        //图片类型
        response.setContentType("image/jpeg");

        // 生成验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(299, 97);

        String code = lineCaptcha.getCode();

        log.info("生成验证码，uuid = " + uuid + ", code = " + code);
        System.out.println("验证码 = " + code);
        // 将验证码的值存储到redis中
        this.adminService.saveVerificationCode(uuid, code);

        // 输出验证码图片
        lineCaptcha.write(response.getOutputStream());

    }

    /**
     * 管理员登陆
     */
    @NoAuthorization
    @PostMapping("login")
    public ErrorResult login(@RequestBody AdminVo adminVo) {
        ErrorResult login = adminService.login(adminVo);
        if (StrUtil.isEmpty(login.getToken())) {
            return ErrorResult.builder().token(null).errCode("0002").errMessage("生成出错").build();
        }
        System.out.println("login.getToken() = " + login.getToken());

        return ErrorResult.builder().token(login.getToken()).errCode("0001").errMessage("生成成功！").build();
    }


    /**
     * 获取个人信息
     */
    @PostMapping("profile")
    public AdminVo profile() {
        Admin admin = AdminThreadLocal.get();
        Admin result = adminService.getById(admin.getId());
        if (result == null) {
            log.error("无法查询到数据");
            return null;
        }
        result.setPassword(null);//不应该返回

        return BeanUtil.toBean(result, AdminVo.class);
    }

    /**
     * 登出
     */
    @PostMapping("logout")
    public Boolean logout() {
        Admin admin = AdminThreadLocal.get();
        AdminThreadLocal.remove();
        return true;
    }
}